package handler

import (
	"comment-master/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Create(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	data := model.User{
		Username: username,
		Password: password,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "nanan" + strconv.Itoa(int(data.ID))
	var Articel model.User
	model.DB.Where("id = ?", data.ID).First(Articel)
	Josgs, _ := json.Marshal(Articel)
	model.DB.Set(redis_key, Josgs)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	data := model.User{

		Username: username,
		Password: password,
	}

	err := model.DB.Find(&data).Order("").Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
	})
	return
}
func PageList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))

	Date := []model.User{}
	err := model.DB.Find(&Date).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "nanan" + strconv.Itoa(2)
	var Articel model.User

	Josgs, _ := json.Marshal(Articel)
	model.DB.Set(redis_key, Josgs)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": page,
		"size": size,
	})
	return
}
